package com.cy.storage.tcc;

import com.cy.storage.entity.Storage;
import com.cy.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StorageTccActionImpl implements StorageTccAction {

    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage = storageMapper.selectById(productId);
        //检查现有库存是否足够使用
        if (storage.getResidue() < count){
            //幂等性解决：当一阶段失败，二阶段不执行
            //库存不足，第一阶段失败，事务失败
            throw new RuntimeException("库存不足");
        }
        storageMapper.updateResidueToFrozen(productId,count);

        //第一阶段成功，保存一个一阶段的成功标记
        ResultHolder.setResult(StorageTccAction.class,ctx.getXid(),"p");

        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {

        if (ResultHolder.getResult(StorageTccAction.class,ctx.getXid()) == null){
            return true;
        }

        storageMapper.updateFrozenToUsed(
                Long.valueOf(ctx.getActionContext("productId").toString()),
                Integer.valueOf(ctx.getActionContext("count").toString()));

        //第二阶段成功，删除标记
        ResultHolder.removeResult(StorageTccAction.class,ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {

        if (ResultHolder.getResult(StorageTccAction.class,ctx.getXid()) == null){
            return true;
        }

        storageMapper.updateFrozenToResidue(
                Long.valueOf(ctx.getActionContext("productId").toString()),
                Integer.valueOf(ctx.getActionContext("count").toString()));

        //第二阶段成功，删除标记
        ResultHolder.removeResult(StorageTccAction.class,ctx.getXid());
        return true;

    }
}
